const $ = layui.jquery;
const getItemUrl = "../item/";
const updateItemUrl = "../item/update/";
const addItemUrl = "../item/add/";
const delItemUrl = "../item/delete/";
const listTreeNodesUrl = "../listTreeNodes/";
const itemDetailUrl = "../itemDetail/";
const viewDocUrl = "../viewDoc/";
const succeedCode = 0;
let dtreeInstance;
let toast;
let curCoverageId = null; // 当前操作的文档 id
layui.use(['dtree', 'jquery', 'element', 'toast', 'code', 'form'], function () {
    const dtree = layui.dtree;
    toast = layui.toast;
    let form = layui.form; // 获得 form 模块对象

    layui.code();

    // 初始化树
    dtreeInstance = dtree.render({
        elem: "#demoTree",
        initLevel: "2",
        method: 'GET',
        dataFormat: "list",  //配置data的风格为list
        url: "../listTreeNode/?cid=1629090043460792322",
        toolbar: true, // 启用toolbar
        toolbarBtn: [addBtn, editBtn],
        toolbarFun: {
            editTreeLoad: myEditTreeLoad,
            editTreeNode: myEditTreeNode,
            addTreeNode: myAddTreeNode,
            delTreeNode: myDelTreeNode
        },
        //toolbarShow:["edit"],  // 只显示编辑功能
        ficon: ["1", "-1"],  // 显示非最后一级节点图标，隐藏最后一级节点图标
        menubar: true ,// 开启menubar
        menubarTips: { // 菜单按钮
            group:["moveDown", "moveUp", "refresh","searchNode",viewDoc]
        }
    });

    // 点击节点触发回调，其中obj内包含丰富的数据，打开浏览器F12查看！
    dtree.on("node('demoTree')", function (obj) {
        console.log("on node click event")
        // 显示元数据项信息
        let eid = obj.param.nodeId;
        let url = itemDetailUrl + eid;
        layer.open({
            type: 2,
            title: "数据项详情",
            content: url,
            maxmin: true
        });
        console.log(obj)
    });

    // 文本输入同步
    inputSync2();

    // 表单提交事件
    let queryForm = $('#queryForm');
    queryForm.submit(function (event) {
        // 阻止表单的默认提交行为
        event.preventDefault();
        // 获取表单数据
        // coverageId=cat
        let formData = queryForm.serialize();
        console.log(formData)
        // 重新渲染 dtree
        dtree.reload("demoTree", {
            url: listTreeNodesUrl + "?" + formData,
            method: "GET",
            initLevel: "2"
        });
        // 更改操作id
        curCoverageId = formData.split("=")[1];
        // 改变标题
        $("#dataTitle").text("元数据目录 ["+curCoverageId+"]");
    })


});

let addBtn = [
    {
        "label": "Name",
        "name": "name",
        "type": "text",
        "verify": "required",
        "placeholder" : "数据项名称（必选）"
    },
    {
        "label": "Namespace",
        "name": "namespace",
        "type": "text",
        "placeholder" : "命名空间（可选）"
    },
    {
        "label": "Order",
        "name": "order",
        "type": "text",
        "placeholder" : "数据项次序（可选）"
    },
    {
        "label": "Attributes",
        "name": "attributes",
        "type": "text",
        "placeholder" : "属性（可选）"
    },
    {
        "label": "Value",
        "name": "value",
        "type": "text",
        "placeholder" : "数据项值（可选）"
    },
];

// 编辑按钮
let editBtn = [
    {
        "label": "Name",
        "name": "name",
        "type": "text",
        "verify": "required",
        "placeholder" : "数据项名称（必选）"
    },
    {
        "label": "Namespace",
        "name": "namespace",
        "type": "text",
        "placeholder" : "命名空间（可选）"
    },
    // order 暂时不能编辑，会破坏树结构
    {
        "label": "Attributes",
        "name": "attributes",
        "type": "text",
        "placeholder" : "属性（可选）"
    },
    {
        "label": "Value",
        "name": "value",
        "type": "text",
        "placeholder" : "数据项值（可选）"
    }
];


// 回填编辑表单
function myEditTreeLoad(treeNode) {
    // 这里可以发送ajax请求，来获取参数值，最后将参数值以form能识别的键值对json的形式返回
    console.log("in myEditTreeLoad")
    console.log(treeNode);

    // 注册事件
    //inputSync();
    // 拼接url
    let eid = treeNode.nodeId;
    let url = getItemUrl + eid;

    $.ajax({
        // ajax基本参数
        url: url,
        type: "GET",
        success: function (result) {
            console.log(result);
            dtreeInstance.changeTreeNodeDone(result);
            // 主动触发一次
            reJoin();
        }
    })
}

// 编辑节点
function myEditTreeNode(treeNode, $div) {
    console.log("in myEditTreeNode")
    console.log(treeNode);
    console.log($div)
    let item = {
        eid: treeNode.nodeId,
        pid: treeNode.parentId,
        name: treeNode.name,
        namespace: treeNode.namespace,
        attributes: treeNode.attributes,
        value: treeNode.value
    }
    console.log(item);
    $.ajax({
        type: "POST",
        data: item,
        url: updateItemUrl,
        success: function (result) {
            console.log(result);
            if (result.code === succeedCode) {
                dtreeInstance.changeTreeNodeEdit(true);// 修改成功
                toast.success({title: 'Info', message: result.message, position: 'topCenter'});
            } else {
                dtreeInstance.changeTreeNodeEdit(false);//修改失败
                toast.error({title: 'Info', message: result.message, position: 'topCenter'});
            }

        },
        error: function (result) {
            console.log(result);
            dtreeInstance.changeTreeNodeEdit(false);//修改失败
            toast.error({title: 'Info', message: result.responseJSON.message, position: 'topCenter'});
        }
    });
}

// 添加节点
function myAddTreeNode(treeNode, $div) {
    console.log("in myAddTreeNode")
    console.log(treeNode);
    console.log($div);
    let item = {
        eid: null,
        pid: treeNode.parentId,
        name: treeNode.name,
        namespace: treeNode.namespace,
        order: treeNode.order,
        attributes: treeNode.attributes,
        value: treeNode.value
    }
    $.ajax({
        type: "POST",
        data: item,
        url: addItemUrl,
        success: function (result) {
            console.log(result);
            if (result.code === succeedCode) {
                // 如果是叶子节点，变为非叶子节点后开启一级图标
                // 因为可能设置了隐藏叶子节点的一级图标
                if (treeNode.leaf === true) {
                    let i = $div.children("i").eq(0);
                    i.removeClass("dtree-icon-hide");
                }
                // 添加成功
                toast.success({title: 'Success', message: result.message, position: 'topCenter'});
                dtreeInstance.changeTreeNodeAdd(true);
            } else {
                toast.error({title: 'Error', message: result.message, position: 'topCenter'});
                dtreeInstance.changeTreeNodeAdd(false);
            }
        },
        error: function (result) {
            dtreeInstance.changeTreeNodeAdd(false); // 添加失败
            toast.error({title: 'Info', message: result.responseJSON.message, position: 'topCenter'});
        }
    });
}

// 删除节点
function myDelTreeNode(treeNode, $div) {
    console.log("in myDelTreeNode")
    console.log(treeNode);
    let delId = {
        eid: treeNode.nodeId
    };
    $.ajax({
        type: "POST",
        data: delId,
        url: delItemUrl,
        success: function (result) {
            console.log(result);
            if (result.code === succeedCode) {
                toast.success({title: 'Success', message: result.message, position: 'topCenter'});
                dtreeInstance.changeTreeNodeDel(true); // 删除成功
            } else {
                toast.error({title: 'Error', message: result.message, position: 'topCenter'});
                dtreeInstance.changeTreeNodeDel(false); // 删除失败
            }
        },
        error: function (result) {
            dtreeInstance.changeTreeNodeDel(false); // 删除失败
            toast.error({title: 'Info', message: result.responseJSON.message, position: 'topCenter'});
        }
    });
}

// 注册 input 事件，显示拼接后的完全限定名
function inputSync() {
    console.log("in inputSync")
    // input
    $('input[name="namespace"]').on("input", reJoin);

    $('input[name="name"]').on("input", reJoin);
}

// 这样可以可以在元素出现前元素就绑定事件
function inputSync2() {
    $(document).on("input", 'input[name="name"]', reJoin);
    $(document).on("input", 'input[name="namespace"]', reJoin);
}

// 连接为 "[namespace] name" 形式
function reJoin() {
    console.log("in reJoin")
    if ($('input[name="namespace"]').val() !== "") {
        $('input[name="editNodeName"]').val(
            "[" + $('input[name="namespace"]').val() + "] " + $('input[name="name"]').val()
        );
        $('input[name="addNodeName"]').val(
            "[" + $('input[name="namespace"]').val() + "] " + $('input[name="name"]').val()
        );
    } else {
        $('input[name="editNodeName"]').val($('input[name="name"]').val());
        $('input[name="addNodeName"]').val($('input[name="name"]').val());
    }
}

// 自定义的菜单按钮
 let viewDoc = {
     menubarId: "viewDoc",  // 按钮的唯一ID
     icon: "dtree-icon-normal-file", // 从 dtreefont 库中选取
     title: "查看文档",  // 按钮的提示标题
     handler: function(node, $div){  //扩展按钮的回调函数
         if (curCoverageId == null) {
             toast.error({title: 'Error', message: "查询数据不能为空", position: 'topCenter'});
             return;
         }
         // 元数据文档信息url
         let url = viewDocUrl + curCoverageId;
         layer.open({
             type: 2,
             title: curCoverageId,
             content: url,
             maxmin: true
         });
     }
 }

